using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework;
using StupidSpaceThing;

namespace RacerGame
{
	internal class Mine : Unit
	{
		public static new int _ProductionCost = 300;
		public override int ProductionTime { get { return _ProductionTime; } }
		public override int ProductionCost { get { return _ProductionCost; } }
		private bool triggered = false;
		public bool Triggered { get { return triggered; } }
		private const float triggerDistance = 30.0f;

		public Mine(Vector3 position)
			: base(new MineEntity(position)) {			
			massModifier = 0;			
		}

		public override void Update(RealGameTime gameTime) {
			if( Position.Z < RacerGame.CurCamera.Position.Z ) {
				entity.Die();
			}
			if( ((entity.Dead && entity.ScaleFactor == 1) || (triggered && !entity.Dead && (Entity as MineEntity).Spin < -0.08f) )
				&& !RacerGame.Ended && !Faction.Defeated && !(Position.Z < RacerGame.CurCamera.Position.Z) ) {
				if( !entity.Dead ) { entity.Die(); }
				RacerGame.CurMap.Bomb(Position2D, 100, -5);
				foreach( Faction f in Faction.Factions ) {
					foreach( FactionEntity fe in f.FactionEntities ) {
						if( fe.Entity.Dead || fe.Faction == Faction ) continue;
						ColObject colObject = fe.Entity.ColObject;
						if( colObject != null ) {
							Vector2 diff = fe.Position2D - Position2D;
							float length = diff.Length();
							diff.Normalize();
							float force = MathHelper.Lerp(10000, 0, ((float)Math.Pow(length, 0.8)) / 15);
							if( force > 0 ) {
								fe.Entity.ColObject.Body.ApplyForce(diff * force);
							}
							float dmg = MathHelper.Lerp(700, 0, ((float)Math.Pow(length, 0.9)) / 16);
							if( dmg > 0 ) {
								fe.Entity.ApplyDamage(dmg, this);
							}
						}
					}
				}
				for( double i = 0; i < Math.PI * 2; i += 0.05f ) {
					Bullets.Fire(new Bullet(Faction.Color, this, new Vector3((float)Math.Sin(i), 0, (float)Math.Cos(i)), Position.Y, gameTime, false));
				}
			} else if(!triggered) {
				if( entity.Life < 100 ) {
					triggered = true;
					entity.Heal(100);
				} else {
					foreach( Faction faction in Faction.Factions ) {
						if( faction == Faction ) continue;
						foreach( Unit unit in faction.Units ) {
							if( !(unit is Mine) && Vector3.Distance(unit.Position, Position) < triggerDistance ) {
								triggered = true;
							}
						}
					}
				}
			} else if( triggered ) {
				(Entity as MineEntity).Spin -= 0.002f;
				if( entity.ScaleFactor < 1 ) {
					entity.ScaleFactor += 0.02f;
				}
			}
			base.Update(gameTime);			
		}
	}
}
